//
//  ESVideoVC.m
//  Eyeshot
//
//  Created by lanou3g on 15/7/2.
//  Copyright (c) 2015年 eyeshot. All rights reserved.
//
#import "ESVideoVCHeader.h"
#import "UMSocial.h"
#import "ESCommentViewController.h"
#import "ESUserDetailViewController.h"
@interface ESVideoVC ()<ESVideoTableViewCellDelegate,ESToolbarDelegate,ESCoverViewDelegate,UMSocialUIDelegate>
@property (nonatomic,strong)NSMutableArray *dataArr;
@property (strong,nonatomic) MPMoviePlayerController *player;
//来接受正在播放视频所在的cell
@property (nonatomic,strong) ESVideoTableViewCell *cell;
//来接受正在播放视频所在的按钮
@property (nonatomic,strong) UIButton *btn;
@property (nonatomic,assign,getter = isLoading) BOOL loading;
@property (nonatomic,assign)NSInteger start;
@property (nonatomic,assign)NSInteger xiugai;
@property (nonatomic,strong) ESCoverView *coverView;
@property (nonatomic, strong) HMFileDownloader *fileDownloader;
//标识沙盒里是否存在缓存视频
@property (nonatomic,assign,getter = isExisting) BOOL existing;
@property (nonatomic,assign)BOOL fullScreen;
@property (nonatomic, strong) ESUserDetailViewController *userDetailVC;//点击头像进入的
@end

@implementation ESVideoVC

//进入用户页面详情
- (void)videoTableViewCell:(ESVideoTableViewCell *)cell didSeletedUserBtn:(ESCellUserProfile *)btn
{
    self.userDetailVC = [[ESUserDetailViewController alloc] init];
    self.userDetailVC.userid = btn.userid;
    [self.navigationController pushViewController:self.userDetailVC animated:YES];
}


- (void)viewWillDisappear:(BOOL)animated
{
    if (self.fullScreen) {
        return;
    }
    //移除通知
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    [self.player.view removeFromSuperview];
    self.cell.playview.hidden = NO;
    [self.player stop];
    self.player = nil;
   
}

- (void)viewWillAppear:(BOOL)animated
{

     [self.tableView reloadData];
}

- (void)viewDidLoad {
    ESLog(@"%@",[NSHomeDirectory() stringByAppendingPathComponent:@"Documents"]);
    [super viewDidLoad];
    _start = 0;
    self.dataArr = [NSMutableArray array];
    [self requestData:_start];
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 70,SCREEN_WIDTH,SCREEN_HEIGHT - 70) style:(UITableViewStylePlain)];
    [self.tableView registerClass:[ESVideoTableViewCell class] forCellReuseIdentifier:@"cell"];
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    //上拉加载
    [self.tableView addLegendFooterWithRefreshingTarget:self refreshingAction:@selector(getMoreData)];
    //下拉刷新
    [self.tableView addLegendHeaderWithRefreshingTarget:self refreshingAction:@selector(refreshDown)];
   
}

- (void)getMoreData
{
    _start += 1;
    [self requestData:_start];
    [self.tableView.footer endRefreshing];
}

- (void)refreshDown
{
    self.loading = YES;
    _start = 0;
    [self requestData:_start];
     [self.tableView.header endRefreshing];
}


- (void)requestData:(NSUInteger)start
{
    ESVideoModel *model =[self.dataArr lastObject];
    NSString *strT= [NSString stringWithFormat:@"%@",model.t];
    NSString *maxtime = strT;
    NSString *str = [NSString stringWithFormat:@"%lu",(unsigned long)start];
    NSString *url = nil;
    if (start == 0) {
        _xiugai++;
        NSString *ss = [NSString stringWithFormat:@"%ld",_xiugai];
        url = [NSString stringWithFormat:URL,self.type,ss,str];
        ESLog(@"%@",url);
        
    }else{
        url = [NSString stringWithFormat:MoreURL,self.type,maxtime,str];
    }
    
    NSURL *kUrl = [NSURL URLWithString:url];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:kUrl];
    request.cachePolicy = NSURLRequestReturnCacheDataElseLoad;
    NSURLCache *cache = [NSURLCache sharedURLCache];
    //    [cache removeAllCachedResponses];
    NSCachedURLResponse *response = [cache cachedResponseForRequest:request];
    if (response) {
//        NSLog(@"---这个请求已经存在缓存");
    } else {
//        NSLog(@"---这个请求没有缓存");
    }
    AFHTTPRequestOperation *op = [[AFHTTPRequestOperation alloc] initWithRequest:request];
    op.responseSerializer = [AFJSONResponseSerializer serializer];
    [op setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, NSDictionary *dict) {
        NSArray *arr = dict[@"list"];
        for (NSDictionary *dic in arr) {
            ESVideoModel *model = [[ESVideoModel alloc] init];
            [model setValuesForKeysWithDictionary:dic];
            //如果模型中的width参数为nil 跳过本次循环
            if (model.width == nil) {
                continue;
            }
            if (self.isLoading) {
                [self.dataArr removeAllObjects];
                self.loading = NO;
            }
            [self.dataArr addObject:model];
        }
        //请求完刷新页面
        [self.tableView reloadData];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"Error: %@", error);
    }];
    [[NSOperationQueue mainQueue] addOperation:op];

    
}

#pragma mark - ESVideoTableViewCellDelegate
- (void)myCell:(ESVideoTableViewCell *)myCell didSelectButton:(UIButton *)btn model:(ESVideoModel *)model
{
     [self.coverView removeFromSuperview];
    if (!self.isExisting) {
        [myCell.indicatorView startAnimating];
        self.cell.playview.hidden = NO;
    }
    //避免同时播放多个视频,移除上个正在播放的视频，并把播放按钮显示出来
    if (self.cell.isPlaying) {
        [self.player.view removeFromSuperview];
        [self.coverView removeFromSuperview];
        self.cell.playview.hidden = NO;
    }
    

    //为了把当前播放视频的myCell传出去
    self.cell = myCell;
    self.btn = btn;
    //创建播放器
#warning 必须把所创建的MPMoviePlayerController设置为属性，否则无法播放，出现黑屏
    if (self.isExisting) {
        NSString *caches = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
        NSString *filepath = [caches stringByAppendingPathComponent:@"video.MP4"];
        self.player = [[MPMoviePlayerController alloc] initWithContentURL:[NSURL fileURLWithPath:filepath]];
    }else {
        self.player = [ESMoviePlayer playerWithUrl:model.videouri];
        _fileDownloader = [[HMFileDownloader alloc] init];
        // 需要下载的文件远程URL
        _fileDownloader.url = model.videouri;
        
        // 文件保存到什么地方
        NSString *caches = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
        NSString *filepath = [caches stringByAppendingPathComponent:@"video.MP4"];
    
        _fileDownloader.destPath = filepath;
        
        __weak typeof(self) weekself = self;
        _fileDownloader.completionHandler = ^{
            NSLog(@"--下载完毕--");
            weekself.existing = YES;
            
        };
        [self.fileDownloader start];
        
    [btn addSubview:myCell.indicatorView];
    }
   
    //为了避免播放开始出现黑屏，播放前先将播放器的view隐藏，等接到播放加载完成通知后显示
    self.player.view.hidden = YES;
    [self.player.view setFrame:btn.bounds];
    [btn addSubview:self.player.view];
    
    
    //点击后关闭自动播放，监听播放通知后播放
    self.player.shouldAutoplay = NO;
    [self.player prepareToPlay];
    //创建通知，监听播放结束后，把播放器视图移除
    NSNotificationCenter *notification = [NSNotificationCenter defaultCenter];
    [notification addObserver:self selector:@selector(moviePlayerPlaybackDidFinish:) name:MPMoviePlayerPlaybackDidFinishNotification  object:self.player];
    //通知全屏播放
    [notification addObserver:self selector:@selector(movieEventFullscreenHandler:) name:MPMoviePlayerWillEnterFullscreenNotification object:self.player];
    //通知退出全屏
    [notification addObserver:self selector:@selector(moviePlayerWillExitFullscreenHandler:) name:MPMoviePlayerWillExitFullscreenNotification object:self.player];
    //监听播放状态改变通知
    [notification addObserver:self selector:@selector(moviePlayerLoadStateDidChange:) name:MPMoviePlayerLoadStateDidChangeNotification object:self.player];
    //监听另一界面发出的移除视频播放的通知
    [notification addObserver:self selector:@selector(remove:) name:@"remove" object:nil];
    
}

- (void)remove:(NSNotification*)notification
{
    [self.coverView removeFromSuperview];
    self.cell.playview.hidden = NO;
    [self.player stop];
    self.player = nil;
}
- (void)moviePlayerLoadStateDidChange:(NSNotification*)notification
{
    //如果是加载完成状态，即可播放状态
    if (MPMovieLoadStatePlaythroughOK) {
        [self.player play];
        self.cell.isPlaying = YES;
        //为了充分避免黑屏出现，等完全进入播放状态后（延迟0.5S）显示播放窗口
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
              self.player.view.hidden = NO;
              [self.cell.indicatorView stopAnimating];
        });
      
       
    }
}

//退出全屏
- (void)moviePlayerWillExitFullscreenHandler:(NSNotification*)notification
{
    [[UIDevice currentDevice] setValue:[NSNumber numberWithInteger:UIInterfaceOrientationPortrait] forKey:@"orientation"];
}

//进图全屏
- (void)movieEventFullscreenHandler:(NSNotification*)notification
{
    self.fullScreen = YES;
    [[UIDevice currentDevice] setValue:[NSNumber numberWithInteger:UIInterfaceOrientationLandscapeRight] forKey:@"orientation"];
}

//播放完成移除播放视图
- (void)moviePlayerPlaybackDidFinish:(NSNotification*)notification
{
    [self.player.view removeFromSuperview];
    self.cell.playview.hidden = YES;
    self.cell.isPlaying = NO;
    //播放结束后加遮幕
    ESCoverView *coverView = [[ESCoverView alloc] init];
    self.coverView = [coverView coverWithFrame:self.btn.bounds SuperView:self.btn];
    self.coverView.delegate = self;
}



#pragma mark -ESCoverViewDelegate

- (void)ESCoverView:(UIView *)view didSelectReplayBtn:(UIButton *)btn
{
     self.existing = YES;
    [self.cell play:(UIButton *)[[btn superview] superview]];

}

- (void)ESCoverView:(UIView *)view didSelectShareBtn:(UIButton *)btn
{
    [UMSocialSnsService presentSnsIconSheetView:self
                                         appKey:@"55955b4c67e58e1c3a000c11"
                                      shareText:@"分享开心从此开始:"
                                     shareImage:[UIImage imageNamed:@"Icon-40"]
                                shareToSnsNames:[NSArray arrayWithObjects:UMShareToSina,UMShareToTencent,UMShareToRenren,UMShareToQzone,UMShareToDouban,UMShareToEmail,UMShareToSms,nil]
                                       delegate:self];
 
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {

    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {

     return self.dataArr.count;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    ESVideoModel *model = self.dataArr[indexPath.row];
    return [ESVideoTableViewCell getHeightForCellByModel:model];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    ESVideoTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];
    
    cell.delegate = self;
    cell.toolbar.delegate = self;
    ESVideoModel *model = self.dataArr[indexPath.row];
    [cell setModel:model];
    
    return cell;
}

#pragma mark - UITableViewDelegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
}
#pragma mark - ESToolbarDelegate

- (void)ESToolbar:(ESToolbar *)toolbar didSelectBtn:(UIButton *)btn
{
    switch (btn.tag) {
        case ESToolbarBtnTypeDing:
        {
            NSURL *url = [NSURL URLWithString:kURL];
            NSURLRequest *request = [NSURLRequest requestWithURL:url cachePolicy:(NSURLRequestUseProtocolCachePolicy) timeoutInterval:15];
            NSOperationQueue *queue = [NSOperationQueue currentQueue];
            [NSURLConnection sendAsynchronousRequest:request queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
            
                [btn setImage:[UIImage imageNamed:@"mainCellDingClickN"] forState:(UIControlStateNormal)];
                
               
            }];
        }
            break;
        case ESToolbarBtnTypeCai:
        {
            ESLog(@"2");
        }
            
            break;
        case ESToolbarBtnTypeShare:
        {
            [UMSocialSnsService presentSnsIconSheetView:self
                                                 appKey:@"55955b4c67e58e1c3a000c11"
                                              shareText:@"分享开心从此开始:"
                                             shareImage:[UIImage imageNamed:@"Icon-40"]
                                        shareToSnsNames:[NSArray arrayWithObjects:UMShareToSina,UMShareToTencent,UMShareToRenren,UMShareToQzone,UMShareToDouban,UMShareToEmail,UMShareToSms,nil]
                                               delegate:self];
        }
            break;
        case ESToolbarBtnTypeComment:
        {
            ESCommentViewController *commentVc = [[ESCommentViewController alloc] init];
            NSIndexPath *indexPath = [self.tableView indexPathForCell:toolbar.parentCell];
            commentVc.model = _dataArr[indexPath.row];
            commentVc.topicType = ESTopicVideo;
            [self.navigationController pushViewController:commentVc animated:YES];
            
        }
            break;
            
    }
}
#pragma mark - UIScrollViewDelegate
-(void)scrollViewDidScroll:(UIScrollView *)scrollView
{
#warning 为了避免视频播放时，用户滑动view，造成视频视图的重用
    //获得当前显示的cell对应的NSIndexPath，并存在数组indexPathArr中
    if (self.cell) {
        NSArray *indexPathArr = [self.tableView indexPathsForVisibleRows];
        //获得正在播放视频的cell的NSIndexPath
        NSIndexPath *indexPath = [self.tableView indexPathForCell:self.cell];
        //判断正在播放视频的cell是否在可见的cell中，如果不在将播放停止
        if (![indexPathArr containsObject:indexPath]) {
            [self.player pause];//此处加pause 是因为避免视图移除了，视频音效还有
            [self.player.view removeFromSuperview];
            [self.coverView removeFromSuperview];
            self.existing = NO;
            self.cell.playview.hidden = NO;
            self.cell.isPlaying = NO;
        }
    }
}


@end
